package com.example.secondhandspringboot.controller;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.constant.GoodsConstant;
import com.example.secondhandspringboot.constant.MessageConstant;
import com.example.secondhandspringboot.constant.RedisConstant;
import com.example.secondhandspringboot.constant.UserConstant;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.dto.GoodsDTO;
import com.example.secondhandspringboot.domain.entity.Goods;
import com.example.secondhandspringboot.domain.entity.User;
import com.example.secondhandspringboot.domain.vo.GoodsVO;
import com.example.secondhandspringboot.exception.GoodsException;
import com.example.secondhandspringboot.exception.UserException;
import com.example.secondhandspringboot.results.PageResult;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.HotSearchService;
import com.example.secondhandspringboot.service.IGoodsService;
import io.netty.util.internal.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周在林
 * @since 2024-04-01
 */
@RestController
@RequestMapping("/goods")
@Slf4j
@CrossOrigin
@RequiredArgsConstructor
@Validated
public class GoodsController {

    private final IGoodsService goodsService;
    private final HotSearchService hotSearchService;
    private final RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取商品
     * @return
     */
    @GetMapping("/getGoods")
    public Result<PageResult<GoodsVO>> getGoods(@RequestParam int page,
                                                @RequestParam int pageSize,
                                                @RequestParam(required = false) String search)
    {
        log.info("分页获取商品 page："+page+",pageSize: "+pageSize+",search: "+search);
        PageResult<GoodsVO> goods = goodsService.getGoods(page, pageSize,search);
        if (goods.getRecords()!=null && !goods.getRecords().isEmpty()){
            //将搜索关键字进行保存处理
            if (!StringUtil.isNullOrEmpty(search)){
                hotSearchService.sortHotSearch(search);
            }
        }
        return Result.success(goods);
    }

    /**
     * 分页获取我发布的所有商品
     * @return
     */
    @GetMapping("/getMyPushGoods")
    public Result<PageResult<GoodsVO>> getMyPushGoods(@RequestParam int page,
                                                            @RequestParam int pageSize){
        log.info("分页获取我发布的所有商品");
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        User user = Db.getById(currentId, User.class);
        if (user == null){
            throw new UserException(MessageConstant.USER_NOT_EXIST);
        }
        PageResult<GoodsVO> listPageResult = goodsService.getMyPushGoods(page, pageSize,currentId);
        return Result.success(listPageResult);
    }

    /**
     * 发布商品
     * @return
     */
    @PostMapping
    public Result pushGoods(@Valid @RequestBody GoodsDTO goodsDTO, HttpServletRequest request){
        log.info("用户发布商品:"+goodsDTO);
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            return Result.error("用户id为空");
        }
        User user = Db.lambdaQuery(User.class)
                .eq(User::getId, currentId)
                .one();
        if (user == null){
            return Result.error(MessageConstant.USER_NOT_EXIST);
        }
        if (goodsDTO.getGoodsName().isEmpty() || goodsDTO.getGoodsName().length()>40){
            return Result.error(MessageConstant.GOODS_NAME_NOT_REQUIRE);
        }
        if (goodsDTO.getDescription().isEmpty() || goodsDTO.getDescription().length()>200)
        {
            return Result.error(MessageConstant.GOODS_DESCRIPTION_NOT_REQUIRE);
        }
        //判断用户是否完善信息，信息完善后可发布商品
        if (Objects.equals(user.getUpdateTime(),user.getCreateTime())){
            return Result.error(MessageConstant.USER_INFO_ABSENCE);
        }
        goodsService.pushGoods(goodsDTO,request);
        return Result.success();
    }

    /**
     * 浏览量加一
     * @return
     */
    @PatchMapping("/incrementLookedNum/{goodsId}")
    public Result incrementLookedNum(@PathVariable Long goodsId){
        Goods goods = goodsService.getById(goodsId);
        if (goods == null){
            return Result.error("当前商品不存在");
        }
        goods.setLookedNums(goods.getLookedNums()+1);
        goodsService.updateById(goods);
        return Result.success();
    }

    /**
     * 获取热门商品
     * @return
     */
    @GetMapping("/getGoodsHotTop")
    public Result<List<GoodsVO>> goodsHotTop(){
        Long currentId = BaseContext.getCurrentId();
        List<GoodsVO> goodsVOList = goodsService.getGoodsHotTop(currentId, GoodsConstant.HOT_TOP_GOODS_NUM);
        return Result.success(goodsVOList);
    }

    /**
     * 删除商品
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result deletedByIds(@PathVariable String ids){
        log.info("删除商品ids:"+ids);
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        if (ids == null){
            throw new GoodsException(MessageConstant.GOODS_DELETED_ERR);
        }
        goodsService.removeBatchByIds(Arrays.asList(ids.split(",")));
        return Result.success();
    }

    /**
     * 今日推荐商品
     * @return
     */
    @GetMapping("/recommendGoods")
    public Result<List<GoodsVO>> recommendToday(){
        Long userId = BaseContext.getCurrentId();
        User user = Db.lambdaQuery(User.class).eq(User::getId, userId).one();
        List<GoodsVO> goodsVOList ;
        //判断是否登录
        if(user != null){
            //返回当前学校商品
            goodsVOList = (List<GoodsVO>) redisTemplate.opsForValue().get(RedisConstant.RECOMMEND_GOODS + user.getSchoolId());
        }else {
            //随机返回
            goodsVOList = goodsService.getRecommendGoods();
        }
        return Result.success(goodsVOList);
    }


    /**
     * 猜你喜欢功能
     * @return
     */
    @GetMapping("/guessLike")
    public Result<List<GoodsVO>> guessLike(){
        log.info("猜你喜欢");
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        List<GoodsVO> goodsVOList = goodsService.guessLike(currentId);
        return Result.success(goodsVOList);
    }

}
